"""
统计报表系统
"""
from datetime import datetime, timedelta
from typing import Dict, List
from collections import defaultdict
from .models import RoomState, BillingDetail


class StatisticsReport:
    """统计报表生成器"""
    
    @staticmethod
    def generate_report(room_states: Dict[str, RoomState], 
                       start_time: datetime = None,
                       end_time: datetime = None) -> dict:
        """生成统计报表
        
        Args:
            room_states: 所有房间状态
            start_time: 开始时间（可选）
            end_time: 结束时间（可选）
            
        Returns:
            统计报表字典
        """
        if end_time is None:
            end_time = datetime.now()
        if start_time is None:
            start_time = end_time - timedelta(days=1)  # 默认统计最近24小时
        
        # 收集符合时间范围的详单
        filtered_details: Dict[str, List[BillingDetail]] = defaultdict(list)
        
        for room_id, room_state in room_states.items():
            for detail in room_state.billing_details:
                if start_time <= detail.start_time <= end_time:
                    filtered_details[room_id].append(detail)
        
        # 统计数据
        total_rooms_used = len(filtered_details)
        total_power = 0.0
        total_cost = 0.0
        total_duration = 0.0
        
        wind_speed_stats = {
            'high': {'count': 0, 'duration': 0.0, 'power': 0.0, 'cost': 0.0},
            'medium': {'count': 0, 'duration': 0.0, 'power': 0.0, 'cost': 0.0},
            'low': {'count': 0, 'duration': 0.0, 'power': 0.0, 'cost': 0.0}
        }
        
        room_stats = []
        
        for room_id, details in filtered_details.items():
            room_power = 0.0
            room_cost = 0.0
            room_duration = 0.0
            room_detail_count = len(details)
            
            for detail in details:
                room_power += detail.power_consumption
                room_cost += detail.cost
                room_duration += detail.duration_minutes
                
                # 按风速统计
                wind_speed = detail.wind_speed
                if wind_speed in wind_speed_stats:
                    wind_speed_stats[wind_speed]['count'] += 1
                    wind_speed_stats[wind_speed]['duration'] += detail.duration_minutes
                    wind_speed_stats[wind_speed]['power'] += detail.power_consumption
                    wind_speed_stats[wind_speed]['cost'] += detail.cost
            
            total_power += room_power
            total_cost += room_cost
            total_duration += room_duration
            
            room_stats.append({
                'room_id': room_id,
                'detail_count': room_detail_count,
                'total_duration_minutes': round(room_duration, 2),
                'total_power_consumption': round(room_power, 3),
                'total_cost': round(room_cost, 2)
            })
        
        # 按费用排序
        room_stats.sort(key=lambda x: x['total_cost'], reverse=True)
        
        return {
            'start_time': start_time.strftime('%Y-%m-%d %H:%M:%S'),
            'end_time': end_time.strftime('%Y-%m-%d %H:%M:%S'),
            'summary': {
                'total_rooms_used': total_rooms_used,
                'total_duration_minutes': round(total_duration, 2),
                'total_power_consumption': round(total_power, 3),
                'total_cost': round(total_cost, 2)
            },
            'wind_speed_statistics': {
                'high': {
                    'usage_count': wind_speed_stats['high']['count'],
                    'total_duration_minutes': round(wind_speed_stats['high']['duration'], 2),
                    'total_power_consumption': round(wind_speed_stats['high']['power'], 3),
                    'total_cost': round(wind_speed_stats['high']['cost'], 2)
                },
                'medium': {
                    'usage_count': wind_speed_stats['medium']['count'],
                    'total_duration_minutes': round(wind_speed_stats['medium']['duration'], 2),
                    'total_power_consumption': round(wind_speed_stats['medium']['power'], 3),
                    'total_cost': round(wind_speed_stats['medium']['cost'], 2)
                },
                'low': {
                    'usage_count': wind_speed_stats['low']['count'],
                    'total_duration_minutes': round(wind_speed_stats['low']['duration'], 2),
                    'total_power_consumption': round(wind_speed_stats['low']['power'], 3),
                    'total_cost': round(wind_speed_stats['low']['cost'], 2)
                }
            },
            'room_statistics': room_stats
        }
    
    @staticmethod
    def format_report_text(report: dict) -> str:
        """格式化报表为文本
        
        Args:
            report: 报表字典
            
        Returns:
            格式化的报表文本
        """
        lines = []
        lines.append("=" * 80)
        lines.append("空调使用统计报表".center(76))
        lines.append("=" * 80)
        lines.append(f"统计时间范围: {report['start_time']} 至 {report['end_time']}")
        lines.append("-" * 80)
        
        # 总体统计
        summary = report['summary']
        lines.append("\n【总体统计】")
        lines.append(f"  使用房间数: {summary['total_rooms_used']}")
        lines.append(f"  总使用时长: {summary['total_duration_minutes']:.2f} 分钟")
        lines.append(f"  总耗电量: {summary['total_power_consumption']:.3f} 度")
        lines.append(f"  总费用: ¥{summary['total_cost']:.2f} 元")
        
        # 风速统计
        lines.append("\n【风速使用统计】")
        wind_stats = report['wind_speed_statistics']
        lines.append(f"{'风速':<10}{'使用次数':<12}{'时长(分钟)':<15}{'耗电量(度)':<15}{'费用(元)':<10}")
        lines.append("-" * 80)
        
        wind_speed_names = {
            'high': '高风',
            'medium': '中风',
            'low': '低风'
        }
        
        for speed_key, speed_name in wind_speed_names.items():
            stats = wind_stats[speed_key]
            lines.append(
                f"{speed_name:<10}"
                f"{stats['usage_count']:<12}"
                f"{stats['total_duration_minutes']:<15.2f}"
                f"{stats['total_power_consumption']:<15.3f}"
                f"{stats['total_cost']:<10.2f}"
            )
        
        # 房间统计
        lines.append("\n【房间使用统计】（按费用降序）")
        lines.append(f"{'房间号':<10}{'使用次数':<12}{'时长(分钟)':<15}{'耗电量(度)':<15}{'费用(元)':<10}")
        lines.append("-" * 80)
        
        for room_stat in report['room_statistics']:
            lines.append(
                f"{room_stat['room_id']:<10}"
                f"{room_stat['detail_count']:<12}"
                f"{room_stat['total_duration_minutes']:<15.2f}"
                f"{room_stat['total_power_consumption']:<15.3f}"
                f"{room_stat['total_cost']:<10.2f}"
            )
        
        lines.append("=" * 80)
        
        return "\n".join(lines)
    
    @staticmethod
    def export_report_to_file(room_states: Dict[str, RoomState],
                            start_time: datetime = None,
                            end_time: datetime = None,
                            filename: str = None) -> str:
        """导出报表到文件
        
        Args:
            room_states: 所有房间状态
            start_time: 开始时间（可选）
            end_time: 结束时间（可选）
            filename: 文件名（可选）
            
        Returns:
            文件路径
        """
        if filename is None:
            timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
            filename = f"report_{timestamp}.txt"
        
        report = StatisticsReport.generate_report(room_states, start_time, end_time)
        text = StatisticsReport.format_report_text(report)
        
        with open(filename, 'w', encoding='utf-8') as f:
            f.write(text)
        
        return filename

